package com.bdqn.controller;

import com.alibaba.fastjson.JSON;
import com.bdqn.pojo.Supplier;
import com.bdqn.pojo.SysUser;
import com.bdqn.service.SupplierService;
import com.bdqn.service.SupplierServiceImpl;
import com.bdqn.util.Page;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 供货商功能模块控制类
 *
 */
@WebServlet("/supplier")
@MultipartConfig(maxFileSize = 1024*1024*2)//标识Servlet支持文件上传
public class SupplierController extends HttpServlet {
    private SupplierService supplierMapper = new SupplierServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码格式
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        System.out.println(request.getParameter("opr"));
        String opr = request.getParameter("opr");
        switch (opr) {
            case "list":
                //查询列表
                list(request, response);
                break;
            case "toAdd":
                //跳转到新增页面
                request.getRequestDispatcher("WEB-INF/jsp/supplier/add.jsp").forward(request, response);
                break;
            case "add":
                //新增
                add(request,response);
                break;
            case "del"://删除
                del(request,response);
                break;
            case "view"://查询详情信息
                view(request,response);
                break;
            case "toUpdate"://进入道修改页面
                toUpdate(request,response);
                break;
            case "update"://修改
                update(request,response);
                break;
        }
    }

    /**
     * 新增
     */
    private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String supCode = request.getParameter("supCode");//供货商编号
        String supName = request.getParameter("supName");//供货商名称
        String supContact = request.getParameter("supContact");//联系人
        String supPhone = request.getParameter("supPhone");//联系电话
        String supAddress = request.getParameter("supAddress");//联系地址
        String supFax = request.getParameter("supFax");//传真
        String supDesc = request.getParameter("supDesc");//备注
        Part companyLicPicPart = request.getPart("companyLicPic");//获取到企业营业执照的Part对象
        String companyLicPicPath = getFileName(request,companyLicPicPart);//企业营业执照路径
        Part orgCodePicPart = request.getPart("orgCodePic");//获取到组织机构代码证的Part对象
        String orgCodePicPath = getFileName(request,orgCodePicPart);//组织机构代码证路径
        Supplier supplier = new Supplier();
        supplier.setSupCode(supCode);
        supplier.setSupName(supName);
        supplier.setSupContact(supContact);
        supplier.setSupPhone(supPhone);
        supplier.setSupAddress(supAddress);
        supplier.setSupFax(supFax);
        supplier.setSupDesc(supDesc);
        supplier.setCompanyLicPicPath(companyLicPicPath);
        supplier.setOrgCodePicPath(orgCodePicPath);
        int add = supplierMapper.add(supplier);
        if(add == 1){
            //新增成功
            list(request,response);
        }else {
            //新增失败
            request.getRequestDispatcher("WEB-INF/jsp/supplier/add.jsp").forward(request,response);
        }
    }

    /**
     * 分页查询
     */
    private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getContextPath();
        System.out.println(path);
        Page<Supplier> page = new Page<>();
        String querySupCode = request.getParameter("querySupCode");//供货商编码
        String querySupName = request.getParameter("querySupName");//供货商名称
        String currPageNoStr = request.getParameter("pageIndex");//查询页码
        int currPageNo = currPageNoStr == null ? 1 : Integer.parseInt(currPageNoStr);
        page.setTotalCount(supplierMapper.count(querySupCode,querySupName));
        page.setCurrPageNo(currPageNo);
        int pageNo = (page.getCurrPageNo() - 1) * page.getPageSize();//查询下标
        List<Supplier> supplierList = supplierMapper.selectPageList(pageNo, page.getPageSize(),querySupCode,querySupName);//查询结果
        request.setAttribute("querySupCode", querySupCode);//供货商编码
        request.setAttribute("querySupName", querySupName);//供货商名称
        request.setAttribute("supplierList", supplierList);//查询列表
        request.setAttribute("totalPageCount", page.getTotalPageCount());//总页码
        request.setAttribute("totalCount", page.getTotalCount());//总记录数
        request.setAttribute("currentPageNo", page.getCurrPageNo());//当前页码
        request.getRequestDispatcher("WEB-INF/jsp/supplier/list.jsp").forward(request, response);
    }

    /**
     * 根据ID删除供货商信息
     */
    private void del(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String idStr = request.getParameter("supId");//指定删除的id
        int id = idStr == null?0: Integer.parseInt(idStr);
        Supplier supplier = supplierMapper.getId(id);
        String delResult = "notexist";//默认用户不存在
        if(supplier!=null) {
            int del = supplierMapper.delete(id);
            System.out.println(del);
            delResult = del == 1 ? "true" : "false";
        }
        Map<String,String> map = new HashMap<>();
        map.put("delResult",delResult);
        // 将对象转换为JSON格式
        String resultJson = JSON.toJSONString(map);
        System.out.println(resultJson);
        response.getWriter().print(resultJson);
        response.getWriter().flush();
        response.getWriter().close();
    }

    /**
     * 查询详情信息
     */
    private void view(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idStr = request.getParameter("supId");//指定查询的id
        int id = idStr == null?0: Integer.parseInt(idStr);
        Supplier supplier = supplierMapper.getId(id);
        request.setAttribute("supplier",supplier);
        request.getRequestDispatcher("WEB-INF/jsp/supplier/view.jsp").forward(request, response);
    }

    /**
     * 进入道修改页面
     */
    private void toUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idStr = request.getParameter("supId");//指定查询的id
        int id = idStr == null?0: Integer.parseInt(idStr);
        Supplier supplier = supplierMapper.getId(id);
        request.setAttribute("supplier",supplier);
        request.getRequestDispatcher("WEB-INF/jsp/supplier/update.jsp").forward(request, response);
    }

    /**
     * 修改
     */
    private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取到修改信息
        String idStr= request.getParameter("id");//修改供货商ID
        int id = idStr == null?0:Integer.parseInt(idStr);
        String supName= request.getParameter("supName");//供货商名称
        String supPhone= request.getParameter("supPhone");//联系电话
        String supContact= request.getParameter("supContact");//联系人
        String supAddress= request.getParameter("supAddress");//联系地址
        String supFax= request.getParameter("supFax");//传真
        String supDesc= request.getParameter("supDesc");//备注
        SysUser upSysUser = (SysUser) request.getSession().getAttribute("USER_SESSION");   //更新者
        Supplier supplier = new Supplier(id,supName,supPhone,supContact,supAddress,supFax,supDesc,upSysUser.getId());
        int upd = supplierMapper.update(supplier);
        if(upd==1){
            //修改成功
            list(request,response);
        }else {
            //修改失败
            request.getRequestDispatcher("WEB-INF/jsp/supplier/update.jsp").forward(request,response);
        }
    }

    /**
     * 上传图片并获取文件名
     * @param request 返回文件名
     * @return
     */
    private String getFileName(HttpServletRequest request, Part part) {
        // 获取添加页面传递过来的参数
        String uploadFilePath = request.getSession().getServletContext().getRealPath("icon/");//上传文件的存储路径（服务器文件系统中的绝对文件路径）
        String fileName="";//文件名
        try{
            File file = new File(uploadFilePath);
            //判断上传路径是否存在，不存在的话先创建一个路径
            if(!file.exists()){
                file.mkdir();
            }
            //获取到Part对象
            Part part2 = part;
            //提取文件名
            fileName = extractFileName(part2);
            //将文件写入到直到指定目录中
            part.write(uploadFilePath+File.separator+fileName);
        }catch (Exception e){
            e.printStackTrace();
        }
        return fileName;
    }

    /**
     * 提取文件名
     * @param part Part对象
     * @return 返回文件名
     */
    private String extractFileName(Part part) {
        String fileName = "";
        String contentDisp = part.getHeader("content-disposition");
        System.out.println(contentDisp);
        String[] items = contentDisp.split(";");
        for (String s: items) {
            if(s.trim().startsWith("filename")){
                fileName = s.substring(s.indexOf("=")+2,s.length()-1);
                break;
            }
        }
        return fileName;
    }
}
